package com.malty.apimanage.service.impl.inner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.malty.apimanage.service.ApiMetaDataService;
import com.malty.apimanage.service.UserApiInfoService;
import com.malty.apimanage.service.UserInfoService;
import com.malty.common.ErrorCode;
import com.malty.common.api.InnerApiMetaDataService;
import com.malty.common.domain.entity.ApiMetaData;
import com.malty.common.domain.entity.UserApiInfo;
import com.malty.common.domain.entity.UserInfo;
import com.malty.common.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Administrator
 * @description 针对表【api_meta_data】的数据库操作Service实现
 * @createDate 2025-09-26 17:09:00
 */
@DubboService
public class InnerApiMetaDataServiceImpl implements InnerApiMetaDataService {
    @Autowired
    private ApiMetaDataService apiMetaDataService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserApiInfoService userApiInfoService;

    @Override
    public ApiMetaData getInterfaceInfo(String path, String method, String accessKey) {
        ApiMetaData apiMetaData = new ApiMetaData();
        apiMetaData.setUrl(path);
        apiMetaData.setMethod(method);
        QueryWrapper<ApiMetaData> apiWrapper = new QueryWrapper<>();
        apiMetaData = apiMetaDataService.getOne(apiWrapper);

        if (apiMetaData == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "接口不存在");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setAccessToken(accessKey);
        QueryWrapper<UserInfo> userWrapper = new QueryWrapper<>(userInfo);
        userInfo = userInfoService.getOne(userWrapper);

        // 接口可用次数校验
        UserApiInfo userApiInfo = userApiInfoService.getUserApiInfo(userInfo.getId(), apiMetaData.getId());
        if (userApiInfo.getAvailableCalls() <= 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "接口次数已用完");
        }

        return apiMetaData;
    }
}




